#include "file.hpp"

void FileRW::Add_File(std::string filename)
{
    _filename = filename;
    _fp = new std::fstream;
}

bool FileRW::isOpened()
{
    return _fp->is_open();
}
void FileRW::close()
{
    _fp->close();
}

int FileRW::File_Clear()
{
    using namespace std;
    _fp->open(_filename, ios::out);
    if (!_fp->is_open()) return -1;
    *_fp << "";
    _fp->close();
    return 0;
}

int FileRW::Save_Data(double data)
{
    using namespace std;
    _fp->open(_filename, ios::out | ios::app);
    if (!_fp->is_open()) return -1;
    _fp->precision(8);
    *_fp << data << endl;
    _fp->close();
    return 0;
}

int FileRW::Save_Data(const OrderedData& data)
{
    return Save_Data(data.o, data.d);
}

int FileRW::Save_Data(int order, double data)
{
    using namespace std;
    _fp->open(_filename, ios::out | ios::app);
    if (!_fp->is_open()) return -1;
    _fp->precision(8);
    *_fp << order << "," << data << endl;
    _fp->close();
    return 0;
}

int FileRW::Load_Data(int order, double* data)
{
    using namespace std;
    int fileorder = -1;
    double filedata = 0;
    string line, number;
    int errcode = -1;
    _fp->open(_filename, ios::in);
    if (!_fp->is_open()) return -1;
    while (getline(*_fp, line)){
        stringstream ss(line);
        if (getline(ss, number, ','))
            fileorder = stoi(number);
        else{
            errcode = 1;  // Error reading file 1
            continue;
        }
        if (getline(ss, number, ','))
            filedata = stod(number);
        else{
            errcode = 2;  // Error reading file 2
            continue;
        }
        if (fileorder == order){
            *data = filedata;
            errcode = 0;
            break;
        }
    }
    _fp->close();
    if (errcode == -1)
        return 3;  // Cannot find specified data
    return errcode;
}
